﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Device.Location;
using System.Linq;
using System.Xml.Linq;
using OneBusAway.Entities;
using OneBusAway.Util;

namespace OneBusAway
{
    public class ViewModel : INotifyPropertyChanged
    {
        public StopWithArrivalsAndDepartures StopCurrent { get; private set; }

        public GeoCoordinateWatcher Geo {get; private set;}

        public IEnumerable<Stop> LocalStops { get; private set; }

        private Stop selectedStop;
        public Stop SelectedStop
        {
            get
            {
                return this.selectedStop;
            }
            set
            {
                if (this.selectedStop == null ||
                    this.selectedStop.Id != value.Id)
                {
                    this.selectedStop = value;
                    this.SignalPropertyChange("SelectedStop");
                }
            }
        }

        public ViewModel()
        {
            XDocument doc = XDocument.Load("current_1_1109.xml");

            this.SelectedStop = XmlHelper.Create<Stop>(doc.Root.Descendants("stop").Where(stop => stop.Element("id").Value == "1_1109").First());
            this.SignalPropertyChange("SelectedStop");

            this.StopCurrent = new StopWithArrivalsAndDepartures();
            this.StopCurrent.ArrivalsAndDepartures = doc.Root.Descendants("arrivalAndDeparture").Select(
                aad => XmlHelper.Create<ArrivalAndDeparture>(aad));

            this.Geo = new GeoCoordinateWatcher();
            this.Geo.MovementThreshold = 20;
            this.Geo.StatusChanged += (o, e) =>
                {
                    this.SignalPropertyChange("Geo");
                };

            this.Geo.PositionChanged += (o, e) =>
                {
                    this.SignalPropertyChange("Geo");
                    
                    XDocument stops = XDocument.Load("stops-for-location.xml");
                    this.LocalStops = stops.Root.Descendants("stop").Select(stop => XmlHelper.Create<Stop>(stop));
                    this.SignalPropertyChange("LocalStops");
                };
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public void SignalPropertyChange(string propertyName)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
